package com.me.test.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


/**
 * 全局的统一返回，
 *
 * @author ME
 * @date 2020/8/3
 */
@RestControllerAdvice(annotations = RestController.class)
@Slf4j
public class GlobalReturnAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        if (String.class.equals(returnType.getGenericParameterType())) {
            try {
                return objectMapper.writeValueAsString(Wrapper.ok(body));
            } catch (JsonProcessingException e) {
                log.error(e.getMessage(), e);
                return "{\"code\": 200, \"msg\": \"success\", \"message\":" + body + "}";
            }
        } else if (body == null) {
            return Wrapper.ok();
        } else if (body instanceof Wrapper) {
            return body;
        }
        return Wrapper.ok(body);
    }
}
